<template>
    <div>
        <!--面包屑导航-->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">分类参数</a></el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert
                    title="注意：只允许为第三级分类设置相关参数！"
                    type="warning"
                    :closable="false"
                    effect="dark">
            </el-alert>
            <el-row class="selectCon">
                <el-col>
                    <span>选择商品分类：</span>
                    <!--级联选择器-->
                    <el-cascader
                            v-model="selectValues"
                            :options="categoriesOptions"
                            :props="cateProps"
                            @change="selectChange"></el-cascader>
                </el-col>
            </el-row>
            <el-tabs v-model="activeName" type="card" @tab-click="tabChangeClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button
                            :disabled="btnIsDisable"
                            type="primary"
                            size="mini"
                            @click="showAddParamsDialog"
                    >添加参数</el-button>
                    <el-table
                            border
                            :data="manyTableData"
                            style="width: 100%">
                        <el-table-column type="expand">
                            <!--展开行-->
                            <template v-slot="scope">
                                <el-tag
                                        :key="index"
                                        v-for="(item, index) in scope.row.attr_vals"
                                        closable
                                        :disable-transitions="false"
                                        @close="attrHandleClose(tag)">
                                    {{item}}
                                </el-tag>
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="attrInputConfirm(scope.row)"
                                        @blur="attrInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column
                                type="index"
                                label="#">
                        </el-table-column>
                        <el-table-column
                                label="参数名称"
                                prop="attr_name">
                        </el-table-column>
                        <el-table-column
                                label="操作"
                                prop="id">
                            <template v-slot="scope">
                                <el-button type="primary"
                                           size="mini"
                                           @click="editParamsDialog(scope.row)"
                                           icon="el-icon-edit">修改</el-button>
                                <el-button type="danger"
                                           size="mini"
                                           icon="el-icon-delete"
										   @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button
                            :disabled="btnIsDisable"
                            type="primary"
                            @click="showAddParamsDialog"
                            size="mini">添加属性</el-button>
                    <el-table
                            border
                            :data="onlyTableData"
                            style="width: 100%">
                        <el-table-column type="expand">
                            <!--展开行-->
                        </el-table-column>
                        <el-table-column
                                type="index"
                                label="#">
                        </el-table-column>
                        <el-table-column
                                label="参数名称"
                                prop="attr_name">
                        </el-table-column>
                        <el-table-column
                                label="操作"
                                prop="id">
                            <template v-slot="scope">
                                <el-button type="primary"
                                           size="mini"
                                           @click="editParamsDialog(scope.row)"
                                           icon="el-icon-edit">修改</el-button>
                                <el-button type="danger"
                                           size="mini"
                                           icon="el-icon-delete"
										   @click="removeParams(scope.row.attr_id)" >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!--添加参数-->
        <el-dialog
                :title="(!addOrEditFlag?'添加':'修改') + titleText"
                :visible.sync="addParamsVisible"
                @close="addParamsOnClose"
                width="50%">
            <el-form :model="addParamsForm" :rules="addParamsRules" ref="addParamsForm" label-width="100px" class="demo-ruleForm">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addParamsForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addParamsVisible = false">取 消</el-button>
                <el-button type="primary" @click="sendAddParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
		data(){
			return{
				testVdom:'虚拟DOM',
				categoriesOptions:[],
				selectValues:[],
				cateProps:{
					expandTrigger:"hover",
					value:"cat_id",
					label:"cat_name",
					children:"children"
				},
				activeName:"many",
				manyTableData:[],
				onlyTableData:[],
				addParamsVisible:false,
				addParamsRules:{
					attr_name:[
						{required:true,message:"请输入参数名称",trigger:"blur"},
						{min:3,max:10,message:'长度在3到5个字符',trigger:"blur"}
					]
				},
				addParamsForm:{
					attr_name:"",
					attr_sel:"",
					arrt_vals:null,
					attr_id:null,
				},
				addOrEditFlag:false,
			};
		},
		created(){
			this.getCategoriesData();
		},
		methods:{
			async getCategoriesData(){
				let {data:res} =await this.$http.get("categories");
				if(res.meta.status !==200) return this.$message.error(res.meta.msg);
				this.categoriesOptions=res.data;
			},
			// 级联选择器回调函数
			selectChange(){
				this.getCategoriesAttrData();
			},
			//切换选项卡
			tabChangeClick(){
				this.getCategoriesAttrData();
			},
			async getCategoriesAttrData(){
				if(this.selectValues.length !==3){
					this.manyTableData=[];
					this.onlyTableData=[];
					this.selectValues=[];
					return this.$message.error("只允许为三级分类设置参数！");
				}
				let {data:res}=await this.$http.get(`categories/${this.cateId}/attributes`,{
					params:{sel:this.activeName}
				});
				res.data.forEach((item,index)=>{
					item.attr_vals=item.attr_vals?item.attr_vals.split(","):[];
					item.inputVisible=false;
					item.inputValue="";
				});
				if(this.activeName==="many"){
					this.manyTableData=res.data;
				}else{
					this.onlyTableData=res.data;
				}
			},
			//展示添加属性框
			showAddParamsDialog(){
				this.addOrEditFlag=false;
				this.addParamsVisible=true;
			},
			
			 
			//点击确定按钮
			sendAddParams(){
				this.$refs.addParamsForm.validate(async (valid)=>{
					if(!valid) return;
					this.addParamsForm.attr_sel=this.activeName;
					if(this.addOrEditFlag){
						var {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${this.addParamsForm.attr_id}`,this.addParamsForm);
						if(res.meta.status !==200) return this.$message.error(res.meta.msg);
					}else{
						var {data:res} =await this.$http.post(`categories/${this.cateId}/attributes`,this.addParamsForm);
						if(res.meta.status !==201) return this.$message.error(res.meta.msg);
					}
					await this.getCategoriesAttrData();
					this.$message.success(res.meta.msg);
					this.addParamsVisible=false;
				});
			
			},
			addParamsOnClose(){
				this.addParamsForm.attr_name="";
				this.$refs.addParamsForm.resetFields();
			},
			// 修改参数
			editParamsDialog(row){
				this.addOrEditFlag=true;
				this.addParamsForm.attr_name=row.attr_name;
				this.addParamsForm.attr_id=row.attr_id;
				this.addParamsVisible=true;
			},

			// 展示参数输入框
			showInput(data){
				data.inputVisible=true;
				this.$nextTick(()=>{
					this.$refs.saveTagInput.focus();
				});
			},
			
			//回车事件
			async attrInputConfirm(data){
				data.inputVisible=false;
				if(!data.inputValue){
					return
				}else{
					if(data.attr_vals.includes(data.inputValue)){
						return this.$message.error("该属性已存在");
					}
					data.attr_vals.push(data.inputValue);
					let sendData={
						attr_name:data.attr_name,
						attr_sel:data.attr_sel,
						attr_vals:data.attr_vals.join(",")
					};
					let {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${data.attr_id}`,sendData);
					if(res.meta.status !==200) return this.$message.error(res.meta.msg);
					this.$message.success(res.meta.msg);
				}
				data.inputValue="";
			},
			 async removeParams(attrId) {
			                const confirmResult = await this.$confirm(
			                    '此操作将永久删除该参数, 是否继续?',
			                    '提示',
			                    {
			                        confirmButtonText: '确定',
			                        cancelButtonText: '取消',
			                        type: 'warning'
			                    }
			                ).catch(err => err)
			
			                // 用户取消了删除的操作
			                if (confirmResult !== 'confirm') {
			                    return this.$message.info('已取消删除！')
			                }

			                // 删除的业务逻辑
			                const {data: res} = await this.$http.delete(
			                    `categories/${this.cateId}/attributes/${attrId}`
			                )
			                if (res.meta.status !== 200) {
			                    return this.$message.error('删除参数失败！')
			                }
			                this.$message.success('删除参数成功！')
			                this.getCategoriesAttrData()
							}
		},
		computed:{
			cateId(){
				return this.selectValues[this.selectValues.length-1]
			},
			btnIsDisable(){
				return this.selectValues.length !==3
			},
			titleText(){
				return this.activeName==="many"?"动态参数":"静态属性"
			}
		}
    };
</script>

<style lang="scss" type="text/scss" scoped>
    .selectCon{
        margin-top: 10px;
    }
    .el-tabs{
        margin-top: 20px;
    }
    .el-tag{
        margin: 5px;
        user-select: none;
    }
    .input-new-tag{
        margin: 0 5px;
        width: 150px;
    }
    .button-new-tag{
        margin-left: 5px;
    }
</style>